package com.UnionPayCenter.service.serviceImpl;

import com.UnionPayCenter.constant.ComponentConstants;
import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.entity.*;
import com.UnionPayCenter.entity.vo.ComponentGrantInfoVo;
import com.UnionPayCenter.entity.vo.TemplateDraftVo;
import com.UnionPayCenter.entity.vo.TemplateVo;
import com.UnionPayCenter.entity.vo.UserVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.enums.ExamineStatusEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.*;
import com.UnionPayCenter.message.resp.TextMessage;
import com.UnionPayCenter.redis.IRedisService;
import com.UnionPayCenter.service.IComponentService;
import com.UnionPayCenter.service.IShopService;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.IWechatService;
import com.UnionPayCenter.sms.StringUtil;
import com.UnionPayCenter.util.MessageUtil;
import com.UnionPayCenter.util.StringUtils;
import com.UnionPayCenter.wechat.ComponentUtil;
import com.UnionPayCenter.wechat.WeixinUtil;
import com.UnionPayCenter.wechat.aes.WXBizMsgCrypt;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ComponentServiceImpl implements IComponentService {
    @Autowired
    private IRedisService redisService;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IShopService shopService;
    @Autowired
    private ShopInfoMapper shopInfoMapper;
    @Autowired
    private ComponentGrantInfoMapper componentGrantInfoMapper;
    @Autowired
    private ConfMapper confMapper;
    @Autowired
    private IWechatService wechatService;

    @Autowired
    private ComponentLogMapper componentLogMapper;
    @Autowired
    private ComponentExamineLogMapper componentExamineLogMapper;

    @Override
    public String openBack(HttpServletRequest request, HttpServletResponse response) {
        String respMessage = null;
        try {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            String msgSignature = request.getParameter("msg_signature");
            log.info(String.format("检验signature:%s, timestamp:%s, nonce:%s, msg_signature:%s", signature, timestamp, nonce, msgSignature));
//            HttpSession session = request.getSession();
            if (!StringUtils.isNotBlank(msgSignature)) { //判断消息是否空
                return signature;
            }

            StringBuilder sb = new StringBuilder();
            BufferedReader in = request.getReader();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            String xml = sb.toString();
            log.info("第三方平台全网发布 原始 Xml=" + xml);
            WXBizMsgCrypt pc = new WXBizMsgCrypt(ComponentConstants.COMPONENT_TOKEN, ComponentConstants.COMPONENT_ENCODINGAESKEY, ComponentConstants.COMPONENT_APPID);
            xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
            log.info("第三方平台全网发布 解密 Xml=" + xml);
            Map<String, Object> xmlToMap = WeixinUtil.xmltoMap(xml);
            String infoType = (String) xmlToMap.get("InfoType");
            if (ComponentConstants.TICKET_INFO_TYPE.equals(infoType)) {
                String ticket = (String) xmlToMap.get("ComponentVerifyTicket");
                //保存验证票据到redis
                redisService.setString(ComponentConstants.TICKET_REDIS_KEY, ticket, 60 * 60, TimeUnit.SECONDS);
                respMessage = "success";
            }
            else if(ComponentConstants.AUTHORIZED_INFO_TYPE.equals(infoType)){
                //TODO 授权成功
                respMessage = "success";
            }
            else if(ComponentConstants.UNAUTHORIZED_INFO_TYPE.equals(infoType)){
                //TODO 取消授权
                //删除授权信息 刷新令牌
                ShopInfoEntity shopInfo = shopService.getByAppid((String) xmlToMap.get("AuthorizerAppid"));
                if(shopInfo != null) {
                    ComponentGrantInfoEntity entity = componentGrantInfoMapper.selectByShop(shopInfo.getShopId());
                    if(entity != null){
                        if(shopInfo.getAppId().equals((String)xmlToMap.get("AuthorizerAppid"))){
                            entity.setAppGrant(0);
                        }
                        if(shopInfo.getWechatId().equals((String)xmlToMap.get("AuthorizerAppid"))){
                            entity.setWechatGrant(0);
                        }
                        entity.setOpenBind(0);
                        componentGrantInfoMapper.updateByPrimaryKeySelective(entity);
                    }
                }
                respMessage = "success";
            }
            else if(ComponentConstants.UPDATEAUTHORIZED_INFO_TYPE.equals(infoType)){
                //TODO 更新授权
                respMessage = "success";
            }
        } catch (Exception e){
            log.error("openBack 处理失败", e);
        }
        return respMessage;
    }

    @Override
    public String findAuthUrl(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String type = jsonParam.getString("type");
            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.DOMAIN_URL);
            String redirectUri = confEntity.getConfValue() + "/templates/authCodeBack/"+shopId;

            String preAuthCode = ComponentUtil.getPreAuthCode();
            if(!StringUtils.isNullStr(preAuthCode)) {
                String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" + ComponentConstants.COMPONENT_APPID + "&pre_auth_code="+preAuthCode+"&redirect_uri=" + redirectUri + "&auth_type=" + (StringUtils.isNullStr(type) ? 3 : type);
                return url;
            }
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "获取预授权码生成授权链接"));
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean authCodeBack(Integer shopId, String authCode) throws Exception {
        JSONObject queryAuth = ComponentUtil.getQueryAuth(authCode);
        //修改授权状态
        String authAppid = queryAuth.getString("authorizer_appid");
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        if(shopInfoEntity != null ){
            ComponentGrantInfoEntity entity = componentGrantInfoMapper.selectByShop(shopId);
            if(entity == null){
                entity = new ComponentGrantInfoEntity();
                entity.setShopId(shopId);
                if(shopInfoEntity.getAppId().equals(authAppid)){
                    entity.setAppGrant(1);
                }
                if(shopInfoEntity.getWechatId().equals(authAppid)){
                    entity.setWechatGrant(1);
                }
                componentGrantInfoMapper.insertSelective(entity);
            }else{
                if(shopInfoEntity.getAppId().equals(authAppid)){
                    entity.setAppGrant(1);
                }
                if(shopInfoEntity.getWechatId().equals(authAppid)){
                    entity.setWechatGrant(1);
                }
                componentGrantInfoMapper.updateByPrimaryKeySelective(entity);
            }

            //获取小程序名称与原始id
            if(shopInfoEntity.getAppId().equals(authAppid)) {
                JSONObject authInfo = ComponentUtil.getAuthInfo(shopInfoEntity.getAppId());
                if (authInfo != null) {
                    JSONObject authorizerInfo = authInfo.getJSONObject("authorizer_info");
                    shopInfoEntity.setAppName(authorizerInfo.getString("nick_name"));
                    shopInfoEntity.setAppLogo(authorizerInfo.getString("head_img"));
                    shopInfoEntity.setAppGhId(authorizerInfo.getString("user_name"));

                    shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
                }
            }
            //获取公众号名称与原始id与logo
            if(shopInfoEntity.getWechatId().equals(authAppid)) {
                JSONObject authInfo = ComponentUtil.getAuthInfo(shopInfoEntity.getWechatId());
                if (authInfo != null) {
                    JSONObject authorizerInfo = authInfo.getJSONObject("authorizer_info");
                    shopInfoEntity.setWechatName(authorizerInfo.getString("nick_name"));
                    shopInfoEntity.setWechatLogo(authorizerInfo.getString("head_img"));
                    shopInfoEntity.setWechatGhId(authorizerInfo.getString("user_name"));

                    shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
                }
            }
        }
        return true;
    }

    @Override
    public String mpBack(String appid, HttpServletRequest request, HttpServletResponse response) {
        String respMessage = "success";
        try {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            String msgSignature = request.getParameter("msg_signature");
            log.info(String.format("mqBack 检验signature:%s, timestamp:%s, nonce:%s, msg_signature:%s", signature, timestamp, nonce, msgSignature));
            if (!StringUtils.isNotBlank(msgSignature)) { //判断消息是否空
                return signature;
            }

            StringBuilder sb = new StringBuilder();
            BufferedReader in = request.getReader();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            String xml = sb.toString();
            log.info("第三方平台mqBack 原始 Xml=" + xml);
            WXBizMsgCrypt pc = new WXBizMsgCrypt(ComponentConstants.COMPONENT_TOKEN, ComponentConstants.COMPONENT_ENCODINGAESKEY, ComponentConstants.COMPONENT_APPID);
            xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
            log.info("第三方平台mqBack 解密 Xml=" + xml);
            Map<String, Object> map = WeixinUtil.xmltoMap(xml);

            if (map != null) {
                String toUserName = (String) map.get("ToUserName");//开发者微信号。
                String fromUserName = (String) map.get("FromUserName");//领券方帐号（一个OpenID）。

                String msgType = (String) map.get("MsgType");//消息类型
                if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
                    String event = (String) map.get("Event");//事件类型
                    //卡券领取事件推送 user_get_card(用户领取卡券)。
                    if (event.equals(MessageUtil.EVENT_TYPE_USER_GET_CARD)) {
                        try {
                            String userCardCode = (String) map.get("UserCardCode");//code序列号。
                            String unionId = (String) map.get("UnionId");//领券用户的UnionId。
                            String cardId = (String) map.get("CardId"); //卡券ID。

                            ShopInfoEntity shopInfo = shopService.getByCardId(cardId);
                            if (shopInfo == null) {
                                return respMessage;
                            }
                            ShopEntity shop = shopMapper.selectByPrimaryKey(shopInfo.getShopId());
                            if (shop == null) {
                                return respMessage;
                            }

                            UserVo vo = userService.getByUnionid(unionId, shopInfo.getShopId());
                            if (vo == null) {
                                return respMessage;
                            } else {
                                vo.setWxOpenid(fromUserName);
                                vo.setWxCard(userCardCode);
                                // 保存公众号openid
                                UserEntity user = new UserEntity();
                                user.setUserId(vo.getUserId());
                                user.setWxOpenid(fromUserName);
                                user.setWxCard(userCardCode);
                                userMapper.updateByPrimaryKeySelective(user);
                            }

                            //发送模版消息
                            wechatService.sendCardMsg(vo, shop, shopInfo);
                            return "success";
                        } catch (Exception e) {
                            return respMessage;
                        }
                    } else if (event.equals(MessageUtil.EVENT_TYPE_USER_VIEW_CARD)) {
                        String userCardCode = (String) map.get("UserCardCode");//code序列号。
                        String unionId = (String) map.get("UnionId");//领券用户的UnionId。
                        String cardId = (String) map.get("CardId"); //卡券ID。

                        try {
                            ShopInfoEntity shopInfo = shopService.getByCardId(cardId);
                            if (shopInfo == null) {
                                return respMessage;
                            }
                            UserVo vo = userService.getByUnionid(unionId, shopInfo.getShopId());
                            if (vo == null) {
                                return respMessage;
                            } else {
                                if (StringUtils.isNullStr(vo.getWxOpenid())) {
                                    // 保存公众号openid
                                    UserEntity user = new UserEntity();
                                    user.setUserId(vo.getUserId());
                                    user.setWxOpenid(fromUserName);
                                    user.setWxCard(userCardCode);
                                    userMapper.updateByPrimaryKeySelective(user);
                                }
                            }

                            return "success";
                        } catch (Exception e) {
                            return respMessage;
                        }
                    } else if (event.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                        String respContent = "感谢关注公众号！";
                        //回复文本消息
                        TextMessage textMessage = new TextMessage();
                        textMessage.setToUserName(fromUserName);
                        textMessage.setFromUserName(toUserName);
                        textMessage.setCreateTime(new Date().getTime());
                        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                        textMessage.setContent(respContent);

                        respMessage = pc.encryptMsg(MessageUtil.textMessageToXml(textMessage), timestamp, nonce);
                    } else if (event.equals(MessageUtil.EVENT_TYPE_WEAPP_AUDIT_SUCCESS) || event.equals(MessageUtil.EVENT_TYPE_WEAPP_AUDIT_FAIL)) {

                        this.updateLastExamineStatus(toUserName);
                        respMessage = "success";
                    }

                }else if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType)) {
                    String content = (String) map.get("Content");
                    log.info("Content###"+content);
                    if("TESTCOMPONENT_MSG_TYPE_TEXT".equals(content)) {
//                        String respContent = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
//                        //回复文本消息
//                        Long createTime = System.currentTimeMillis()/1000;
//                        TextMessage textMessage = new TextMessage();
//                        textMessage.setToUserName(fromUserName);
//                        textMessage.setFromUserName(toUserName);
//                        textMessage.setCreateTime(createTime);
//                        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
//                        textMessage.setContent(respContent);
//                        textMessage.setFuncFlag(0);
//                        log.info("respMessage 加密前:" +MessageUtil.textMessageToXml(textMessage));
//                        respMessage = pc.encryptMsg(MessageUtil.textMessageToXml(textMessage), createTime+"", nonce);
//                        log.info("respMessage 加密后:" +respMessage);

                        StringBuilder sendToWechatXml = new StringBuilder(); //构造回复的字符串
                        sendToWechatXml.append("<xml>");
                        sendToWechatXml.append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>");
                        sendToWechatXml.append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>");
                        sendToWechatXml.append("<CreateTime>" + System.currentTimeMillis() + "</CreateTime>");
                        sendToWechatXml.append("<MsgType><![CDATA[text]]></MsgType>");
                        sendToWechatXml.append("<Content><![CDATA[TESTCOMPONENT_MSG_TYPE_TEXT_callback]]></Content>");
                        sendToWechatXml.append("</xml>");

                        log.info("respMessage 加密前:" + sendToWechatXml.toString());
                        respMessage = pc.encryptMsg(sendToWechatXml.toString(), timestamp, nonce);
                        log.info("respMessage 加密后:" + respMessage);
                    }else if(content.contains("QUERY_AUTH_CODE:")){
                        String con = content.replace("QUERY_AUTH_CODE:", "");

                        JSONObject authInfo = ComponentUtil.getQueryAuth(con);
                        new Thread() {
                            public void run() {
                                try {
                                    Thread.sleep(5000);
                                    String authAppid = authInfo.getString("authorizer_appid");
                                    ComponentUtil.send(authAppid, fromUserName, con+"_from_api");
                                } catch (Exception e) {
                                    log.error("全网发布api发送消息", e);
                                }
                            }
                        }.start();

                        return "";
                    }else{
                        String respContent = "你好，感谢关注！";
                        //回复文本消息
                        TextMessage textMessage = new TextMessage();
                        textMessage.setToUserName(fromUserName);
                        textMessage.setFromUserName(toUserName);
                        textMessage.setCreateTime(new Date().getTime()/1000);
                        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                        textMessage.setContent(respContent);

                        respMessage = pc.encryptMsg(MessageUtil.textMessageToXml(textMessage), timestamp, nonce);
                    }
                }else{
                    respMessage = "success";
                }
            }
        }catch (Exception e){
            log.error("第三方mpBack 处理失败", e);
        }


        return respMessage;
    }

    public void updateLastExamineStatus(String toUserName) {
        try {
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByAppGhId(toUserName);
            if(shopInfoEntity != null){
                this.selectAndUpdateLastExamineStatus(shopInfoEntity.getShopId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean openBind(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            return openBinds(shopId);
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean openBinds(Integer shopId) throws Exception {
        ComponentGrantInfoEntity entity = componentGrantInfoMapper.selectByShop(shopId);
        //未授权 返回失败
        if(entity == null || entity.getAppGrant() == 0 || entity.getWechatGrant() == 0){
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "公众号/小程序未授权，绑定"));
        }
        //未绑定
        if(entity.getOpenBind() == 0){
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
            String openAppid = shopInfoEntity.getOpenAppid();
            //公众号/小程序绑定的开发平台
            String appBind = ComponentUtil.openGet(shopInfoEntity.getAppId());
            String wechatBind = ComponentUtil.openGet(shopInfoEntity.getWechatId());

            //商铺未生成第三方开放平台
            if(StringUtils.isNullStr(openAppid)){
                if(StringUtils.isNullStr(appBind) && StringUtils.isNullStr(wechatBind)){
                    //创建开放平台
                    String bind = ComponentUtil.openCreate(shopInfoEntity.getAppId());
                    //绑定到创建的开放平台
                    ComponentUtil.openBind(bind, shopInfoEntity.getWechatId());

                    //修改开放平台appid
                    shopInfoEntity.setOpenAppid(bind);
                    //修改绑定状态
                    entity.setOpenBind(1);
                }else if(!StringUtils.isNullStr(appBind) && !StringUtils.isNullStr(wechatBind)){
                    if(!appBind.equals(wechatBind)){
                        throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "公众号/小程序绑定的开放平台不一致，绑定"));
                    }else{
                        //修改开放平台appid
                        shopInfoEntity.setOpenAppid(appBind);
                        //修改绑定状态
                        entity.setOpenBind(1);
                    }
                }else if(!StringUtils.isNullStr(appBind) && StringUtils.isNullStr(wechatBind)){
                    //绑定到小程序绑定的开放平台
                    ComponentUtil.openBind(appBind, shopInfoEntity.getWechatId());
                    //修改开放平台appid
                    shopInfoEntity.setOpenAppid(appBind);
                    //修改绑定状态
                    entity.setOpenBind(1);
                }else if(StringUtils.isNullStr(appBind) && !StringUtils.isNullStr(wechatBind)){
                    //绑定到公众号绑定的开放平台
                    ComponentUtil.openBind(wechatBind, shopInfoEntity.getAppId());
                    //修改开放平台appid
                    shopInfoEntity.setOpenAppid(wechatBind);
                    //修改绑定状态
                    entity.setOpenBind(1);
                }
            }
            //商铺已生成第三方开放平台
            else{
                if(!StringUtils.isNullStr(appBind) && !openAppid.equals(appBind)){
                    throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "小程序已绑定其他开放平台，绑定"));
                }
                if(!StringUtils.isNullStr(wechatBind) && !openAppid.equals(appBind)){
                    throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "公众号已绑定其他开放平台，绑定"));
                }
                if(StringUtils.isNullStr(appBind)){
                    ComponentUtil.openBind(openAppid, shopInfoEntity.getAppId());
                }
                if(StringUtils.isNullStr(wechatBind)){
                    ComponentUtil.openBind(openAppid, shopInfoEntity.getWechatId());
                }
                //修改绑定状态
                entity.setOpenBind(1);
            }

            //公众号关联小程序
            if(entity.getRelation() == 0) {
                ComponentUtil.wxLink(shopInfoEntity.getAppId(), shopInfoEntity.getWechatId());
                //修改关联状态
                entity.setRelation(1);
            }

            //设置小程序服务器域名
            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.LEGAL_URL);
            JSONArray requestdomain = new JSONArray();
            requestdomain.add(confEntity.getConfValue());

            JSONArray wsrequestdomain = new JSONArray();
            wsrequestdomain.add(confEntity.getConfValue().replace("http://", "ws://").replace("https://", "wss://"));

            JSONArray uploaddomain = new JSONArray();
            uploaddomain.add(confEntity.getConfValue());

            JSONArray downloaddomain = new JSONArray();
            downloaddomain.add(confEntity.getConfValue());
            //第三方现未添加
            downloaddomain.add("https://wx.qlogo.cn");

            ComponentUtil.modifyDomain(shopInfoEntity.getAppId(), "set", requestdomain, wsrequestdomain, uploaddomain, downloaddomain);

            //设置小程序业务域名
            JSONArray webviewdomain = new JSONArray();
            webviewdomain.add(confEntity.getConfValue());
            ComponentUtil.setWebViewDomain(shopInfoEntity.getAppId(), "set", webviewdomain);

            //获取小程序模版消息id并保存
            //获取 支付推送小程序模版id
            if(StringUtils.isNullStr(shopInfoEntity.getPayTemplateId())) {
                JSONArray pay = new JSONArray();
                pay.add(11);
                pay.add(6);
                pay.add(9);
                pay.add(12);
                String payTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT0009", pay);

                shopInfoEntity.setPayTemplateId(payTemplateId);
            }
            //获取 充值推送小程序模版id
            if(StringUtils.isNullStr(shopInfoEntity.getDepositTemplateId())) {
                JSONArray deposit = new JSONArray();
                deposit.add(4);
                deposit.add(10);
                deposit.add(14);
                deposit.add(3);
                deposit.add(7);
                String depositTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT0016", deposit);

                shopInfoEntity.setDepositTemplateId(depositTemplateId);
            }
            //获取 卡券推送小程序模版id
            if(StringUtils.isNullStr(shopInfoEntity.getCardTemplateId())) {
                JSONArray card = new JSONArray();
                card.add(2);
                card.add(6);
                card.add(16);
                card.add(3);
                String cardTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT2266", card);

                shopInfoEntity.setCardTemplateId(cardTemplateId);
            }

            shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
            componentGrantInfoMapper.updateByPrimaryKeySelective(entity);
        }
        return true;
    }

    @Override
    public boolean allSubmitAudit(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            String templateId = jsonParam.getString("templateId");
            String userVersion = jsonParam.getString("userVersion");
            String userDesc = jsonParam.getString("userDesc");

            //查询需要提交的商铺
            List<ComponentGrantInfoEntity> list = componentGrantInfoMapper.selectToExamine();
            if(list != null) {
                for (ComponentGrantInfoEntity entity:list) {
                    try {
                        String auditid = this.oneCommitAndSubmit(managerId, entity.getShopId(), templateId, userVersion, userDesc);

                        ComponentLogEntity logEntity = new ComponentLogEntity();
                        logEntity.setManagerId(managerId);
                        logEntity.setType(2);
                        logEntity.setBizId(templateId);
                        logEntity.setBizDesc("商铺编号：" + entity.getShopId() + "，审核id：" + auditid+ "，经全部提交审核，操作结果：成功");
                        componentLogMapper.insertSelective(logEntity);

                    }catch (Exception e){
                        ComponentLogEntity logEntity = new ComponentLogEntity();
                        logEntity.setManagerId(managerId);
                        logEntity.setType(2);
                        logEntity.setBizId(templateId);
                        logEntity.setBizDesc("商铺编号：" + entity.getShopId() + "，经全部提交审核，操作结果：失败， 原因：" + e.getMessage());
                        componentLogMapper.insertSelective(logEntity);
                    }
                }
            }
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public boolean allRelease(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            //查询需要提交的商铺
            List<ComponentGrantInfoEntity> list = componentGrantInfoMapper.selectToRelease();
            if(list != null) {
                for (ComponentGrantInfoEntity entity : list) {
                    try {
                        boolean isSucc = this.oneRelease(entity.getShopId());
                        if (isSucc) {
                            ComponentLogEntity logEntity = new ComponentLogEntity();
                            logEntity.setManagerId(managerId);
                            logEntity.setType(3);
                            logEntity.setBizId("");
                            logEntity.setBizDesc("商铺编号：" + entity.getShopId() + "，经全部发布，操作结果：成功");
                            componentLogMapper.insertSelective(logEntity);
                        } else {
                            ComponentLogEntity logEntity = new ComponentLogEntity();
                            logEntity.setManagerId(managerId);
                            logEntity.setType(3);
                            logEntity.setBizId("");
                            logEntity.setBizDesc("商铺编号：" + entity.getShopId() + "，经全部发布，操作结果：失败");
                            componentLogMapper.insertSelective(logEntity);
                        }
                    } catch (Exception e) {
                        ComponentLogEntity logEntity = new ComponentLogEntity();
                        logEntity.setManagerId(managerId);
                        logEntity.setType(3);
                        logEntity.setBizId("");
                        logEntity.setBizDesc("商铺编号：" + entity.getShopId() + "，经全部发布，操作结果：失败， 原因：" + e.getMessage());
                        componentLogMapper.insertSelective(logEntity);
                    }
                }
            }
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public boolean wxLink(Integer shopId) throws Exception {
        ComponentGrantInfoEntity entity = componentGrantInfoMapper.selectByShop(shopId);
        //未授权 返回失败
        if(entity == null){
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "公众号/小程序未授权，绑定"));
        }
        if(entity.getRelation() == 0) {
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
            ComponentUtil.wxLink(shopInfoEntity.getAppId(), shopInfoEntity.getWechatId());
            //修改关联状态
            entity.setRelation(1);
            componentGrantInfoMapper.updateByPrimaryKeySelective(entity);
        }
        return true;
    }

    @Override
    public boolean serviceTemplatesSave(Integer shopId) throws Exception {
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        //获取 支付推送小程序模版id
        JSONArray pay = new JSONArray();
        pay.add(11);
        pay.add(6);
        pay.add(9);
        pay.add(12);
        String payTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT0009", pay);

        //获取 充值推送小程序模版id
        JSONArray deposit = new JSONArray();
        deposit.add(4);
        deposit.add(10);
        deposit.add(14);
        deposit.add(3);
        deposit.add(7);
        String depositTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT0016", deposit);

        //获取 卡券推送小程序模版id
        JSONArray card = new JSONArray();
        card.add(2);
        card.add(6);
        card.add(16);
        card.add(3);
        String cardTemplateId = ComponentUtil.serviceTemplate(shopInfoEntity.getAppId(), "AT2266", card);

        shopInfoEntity.setPayTemplateId(payTemplateId);
        shopInfoEntity.setDepositTemplateId(depositTemplateId);
        shopInfoEntity.setCardTemplateId(cardTemplateId);
        shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
        return true;
    }

    @Override
    public PageInfo<ComponentGrantInfoVo> findAuthList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            //页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            //每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            Integer status = jsonParam.getInteger("status");
            String appName = jsonParam.getString("appName");

            PageHelper.startPage(page, pageSize);

            List<ComponentGrantInfoVo> list = componentGrantInfoMapper.findAuthList(status, appName);
            PageInfo<ComponentGrantInfoVo> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public PageInfo<TemplateDraftVo> findTemplateDraftList(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            JSONArray array = ComponentUtil.getTemplateDraftList();
            List<TemplateDraftVo> list = JSONObject.parseArray(array.toJSONString(),  TemplateDraftVo.class);
            Collections.reverse(list);
            PageInfo<TemplateDraftVo> pageInfo = new PageInfo<>(list);
            return pageInfo;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public boolean addToTemplate(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            String draftId = jsonParam.getString("draftId");
            try {
                //判断是否记录过多
                JSONArray array = ComponentUtil.getTemplateList();
                if(array!=null) {
                    List<TemplateVo> list = JSONObject.parseArray(array.toJSONString(), TemplateVo.class);
                    if (list.size() > 40) {
                        List<TemplateVo> collect = list.stream().sorted(Comparator.comparing(TemplateVo::getTemplate_id).reversed()).collect(Collectors.toList());
                        for (int i = 40; i < collect.size(); i++) {
                            ComponentUtil.deleteTemplate(collect.get(i).getTemplate_id()+"");
                        }
                    }
                }

                boolean isSucc = ComponentUtil.addToTemplate(draftId);

                //修改已发布/审核被拒/已撤回的状态为待审核
                componentGrantInfoMapper.updateToWaitCommit();

                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(0);
                logEntity.setBizId(draftId);
                logEntity.setBizDesc("添加草稿到模版库，操作结果：成功");
                componentLogMapper.insertSelective(logEntity);

                //获取最新一个模版信息存入缓存
                array = ComponentUtil.getTemplateList();
                if(array!=null) {
                    List<TemplateVo> list = JSONObject.parseArray(array.toJSONString(), TemplateVo.class);
                    List<TemplateVo> collect = list.stream().sorted(Comparator.comparing(TemplateVo::getTemplate_id).reversed()).collect(Collectors.toList());
                    redisService.setString(ComponentConstants.LAST_TEMPLSTES_ID_REDIS_KEY, collect.get(0).getTemplate_id()+"");
                }

                return isSucc;
            }catch (Exception e){
                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(0);
                logEntity.setBizId(draftId);
                logEntity.setBizDesc("添加草稿到模版库，操作结果：失败，原因：" + e.getMessage());
                componentLogMapper.insertSelective(logEntity);

                throw e;
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public PageInfo<TemplateVo> findTemplateList(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            JSONArray array = ComponentUtil.getTemplateList();
            List<TemplateVo> list = JSONObject.parseArray(array.toJSONString(),  TemplateVo.class);
            List<TemplateVo> collect = list.stream().sorted(Comparator.comparing(TemplateVo::getTemplate_id).reversed()).collect(Collectors.toList());
            PageInfo<TemplateVo> pageInfo = new PageInfo<>(collect);
            return pageInfo;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public boolean deleteTemplate(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            String templateId = jsonParam.getString("templateId");

            try {
                boolean isSucc = ComponentUtil.deleteTemplate(templateId);

                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(1);
                logEntity.setBizId(templateId);
                logEntity.setBizDesc("删除代码库模版，操作结果：成功");
                componentLogMapper.insertSelective(logEntity);

                return isSucc;
            }catch (Exception e){
                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(1);
                logEntity.setBizId(templateId);
                logEntity.setBizDesc("删除代码库模版，操作结果：失败， 原因：" + e.getMessage());
                componentLogMapper.insertSelective(logEntity);
                throw e;
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    @Override
    public boolean submitAudit(JSONObject jsonParam) throws Exception{
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            Integer shopId = jsonParam.getInteger("shopId");
            String templateId = jsonParam.getString("templateId");
            String userVersion = jsonParam.getString("userVersion");
            String userDesc = jsonParam.getString("userDesc");

            //上传代码并提交审核
            try {
                String auditid = this.oneCommitAndSubmit(managerId, shopId, templateId, userVersion, userDesc);

                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(2);
                logEntity.setBizId(templateId);
                logEntity.setBizDesc("商铺编号：" + shopId + "，审核id：" + auditid+ "提交审核，操作结果：成功");
                componentLogMapper.insertSelective(logEntity);

                return true;
            }catch (Exception e){
                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(2);
                logEntity.setBizId(templateId);
                logEntity.setBizDesc("商铺编号：" + shopId + "提交审核，操作结果：失败， 原因：" + e.getMessage());
                componentLogMapper.insertSelective(logEntity);

                throw e;
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    public String oneCommitAndSubmit(Integer managerId, Integer shopId, String templateId, String userVersion, String userDesc) throws Exception{
        ComponentGrantInfoEntity componentGrantInfoEntity = componentGrantInfoMapper.selectByShop(shopId);
        if(componentGrantInfoEntity.getOpenBind() == 1 && componentGrantInfoEntity.getExamineStatus() != 0 && componentGrantInfoEntity.getExamineStatus() != 2 && componentGrantInfoEntity.getExamineStatus() != 4 ) {
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
            JSONObject ext = new JSONObject();
            ext.put("appid", shopInfoEntity.getAppId());
            ext.put("appsecret", shopInfoEntity.getAppSecret());
            ext.put("shopId", shopId);
            ext.put("cardId", shopInfoEntity.getMembercardId());
            ext.put("appName", shopInfoEntity.getAppName());

            JSONObject extJson = new JSONObject();
            extJson.put("ext", ext);
            extJson.put("extAppid", shopInfoEntity.getAppId());

            //上传代码
            ComponentUtil.codeCommit(shopInfoEntity.getAppId(), templateId, extJson.toJSONString(), userVersion, userDesc);

            //获取已上传的代码的页面列表
            JSONArray page = ComponentUtil.codeGetPage(shopInfoEntity.getAppId());
            if (page != null) {
                //获取审核时可填写的类目信息
                JSONArray category = ComponentUtil.getCategory(shopInfoEntity.getAppId());
                if (category != null) {
                    JSONObject item = new JSONObject();
                    item.put("address", page.get(0));
                    item.put("first_class", category.getJSONObject(0).getString("first_class"));
                    item.put("second_class", category.getJSONObject(0).getString("second_class"));
                    item.put("first_id", category.getJSONObject(0).getString("first_id"));
                    item.put("second_id", category.getJSONObject(0).getString("second_id"));
                    item.put("title", "首页");

                    JSONArray itemList = new JSONArray();
                    itemList.add(item);
                    //提交审核
                    String auditid = ComponentUtil.codeSubmitAudit(shopInfoEntity.getAppId(), itemList);

                    //添加提审记录
                    ComponentExamineLogEntity componentExamineLogEntity = new ComponentExamineLogEntity();
                    componentExamineLogEntity.setManagerId(managerId);
                    componentExamineLogEntity.setShopId(shopId);
                    componentExamineLogEntity.setTemplateId(Integer.valueOf(templateId));
                    componentExamineLogEntity.setUserVersion(userVersion);
                    componentExamineLogEntity.setUserDesc(userDesc);
                    componentExamineLogEntity.setExamineStatus(2);
                    componentExamineLogEntity.setAuditid(auditid);
                    componentExamineLogMapper.insertSelective(componentExamineLogEntity);

                    //修改审核状态
                    componentGrantInfoEntity.setExamineStatus(2);
                    componentGrantInfoEntity.setExamineReason("/");
                    componentGrantInfoEntity.setExamineScreenshot("");
                    componentGrantInfoEntity.setTemplateId(Integer.valueOf(templateId));
                    componentGrantInfoEntity.setUserVersion(userVersion);
                    componentGrantInfoEntity.setUserDesc(userDesc);
                    componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);

                    return auditid;
                }
            }
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(),"提交审核"));
        }else {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(),"未授权或者已提交，提交审核"));
        }
    }

    @Override
    public boolean release(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            Integer shopId = jsonParam.getInteger("shopId");

            //发布
            try {
                boolean isSucc = this.oneRelease(shopId);
                if(isSucc){
                    ComponentLogEntity logEntity = new ComponentLogEntity();
                    logEntity.setManagerId(managerId);
                    logEntity.setType(3);
                    logEntity.setBizId("");
                    logEntity.setBizDesc("商铺编号：" + shopId + "发布，操作结果：成功");
                    componentLogMapper.insertSelective(logEntity);

                    return true;
                }else{
                    ComponentLogEntity logEntity = new ComponentLogEntity();
                    logEntity.setManagerId(managerId);
                    logEntity.setType(3);
                    logEntity.setBizId("");
                    logEntity.setBizDesc("商铺编号：" + shopId + "发布，操作结果：失败");
                    componentLogMapper.insertSelective(logEntity);
                    return  false;
                }
            }catch (Exception e){
                ComponentLogEntity logEntity = new ComponentLogEntity();
                logEntity.setManagerId(managerId);
                logEntity.setType(3);
                logEntity.setBizId("");
                logEntity.setBizDesc("商铺编号：" + shopId + "发布，操作结果：失败， 原因：" + e.getMessage());
                componentLogMapper.insertSelective(logEntity);

                throw e;
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    public boolean oneRelease(Integer shopId) throws Exception{
        ComponentGrantInfoEntity componentGrantInfoEntity = componentGrantInfoMapper.selectByShop(shopId);
        if(componentGrantInfoEntity.getOpenBind() == 1 && componentGrantInfoEntity.getExamineStatus() == ExamineStatusEnum.SUCC.code()) {
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);

            JSONObject json = ComponentUtil.codeGetLatestAuditstatus(shopInfoEntity.getAppId());
            String auditid = json.getString("auditid");
            if("0".equals(json.getString("status"))) {
                ComponentUtil.codeRelease(shopInfoEntity.getAppId());

                //修改审核记录状态为发布成功
                ComponentExamineLogEntity componentExamineLogEntity = new ComponentExamineLogEntity();
                componentExamineLogEntity.setShopId(shopId);
                componentExamineLogEntity.setAuditid(auditid);
                componentExamineLogEntity.setExamineStatus(ExamineStatusEnum.RELEASE.code());
                componentExamineLogMapper.updateByAuditid(componentExamineLogEntity);

                //修改审核状态
                componentGrantInfoEntity.setExamineStatus(ExamineStatusEnum.RELEASE.code());
                componentGrantInfoEntity.setExamineReason("/");
                componentGrantInfoEntity.setExamineScreenshot("");

                //判断是否为最新模版提交审核
                String templatesId = redisService.getString(ComponentConstants.LAST_TEMPLSTES_ID_REDIS_KEY);
                if(!StringUtils.isNullStr(templatesId)){
                    if(Integer.valueOf(templatesId) > componentGrantInfoEntity.getTemplateId()){
                        componentGrantInfoEntity.setExamineStatus(ExamineStatusEnum.WAIT.code());
                    }
                }

                componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);
                return true;
            }else{
                //修改审核记录状态
                ComponentExamineLogEntity componentExamineLogEntity = new ComponentExamineLogEntity();
                componentExamineLogEntity.setShopId(shopId);
                componentExamineLogEntity.setAuditid(auditid);
                componentExamineLogEntity.setExamineStatus(json.getInteger("status"));
                componentExamineLogMapper.updateByAuditid(componentExamineLogEntity);

                //修改审核状态
                componentGrantInfoEntity.setExamineStatus(json.getInteger("status"));
                componentGrantInfoEntity.setExamineReason(json.getString("reason"));
                componentGrantInfoEntity.setExamineScreenshot(json.getString("ScreenShot"));
                componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);
                return false;
            }
        }else {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(),"未授权或者已提交，提交审核"));
        }
    }


    @Override
    public ComponentExamineLogEntity findLastExamineStatus(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        ManagerEntity managerEntity = managerMapper.selectByPrimaryKey(managerId);
        if (managerEntity != null && managerEntity.getIsAdmin() == 0) {
            Integer shopId = jsonParam.getInteger("shopId");

            ComponentExamineLogEntity componentExamineLogEntity = this.selectAndUpdateLastExamineStatus(shopId);
            return componentExamineLogEntity;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "管理员不存在或不为超级管理员，managerId"));
        }
    }

    public ComponentExamineLogEntity selectAndUpdateLastExamineStatus(Integer shopId) throws Exception {
        ComponentGrantInfoEntity componentGrantInfoEntity = componentGrantInfoMapper.selectByShop(shopId);

        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);

        JSONObject json = ComponentUtil.codeGetLatestAuditstatus(shopInfoEntity.getAppId());
        String auditid = json.getString("auditid");
        ComponentExamineLogEntity componentExamineLogEntity = componentExamineLogMapper.selectByAuditid(shopId, auditid);
        if(componentExamineLogEntity == null){
            componentGrantInfoEntity.setExamineStatus(json.getInteger("status"));
            componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);
            return componentExamineLogEntity;
        }else if(componentExamineLogEntity.getExamineStatus() == 4){
            if(componentGrantInfoEntity.getExamineStatus() != 4) {
                componentGrantInfoEntity.setExamineStatus(4);
                componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);
            }
            return componentExamineLogEntity;
        }else{
            //修改审核记录状态
            componentExamineLogEntity.setExamineStatus(json.getInteger("status"));
            componentExamineLogMapper.updateByPrimaryKeySelective(componentExamineLogEntity);

            //修改审核状态
            componentGrantInfoEntity.setExamineStatus(json.getInteger("status"));
            componentGrantInfoEntity.setExamineReason(json.getString("reason"));
            componentGrantInfoEntity.setExamineScreenshot(json.getString("ScreenShot"));
            componentGrantInfoMapper.updateByPrimaryKeySelective(componentGrantInfoEntity);

            return componentExamineLogEntity;
        }
    }
}
